#include <iostream>
#include <string>
#include <vector>
#include <fstream>

int checkParams(int argc, char** argv)
{
    if(argc < 3)
    {
        std::cout << "请输入程序的可执行路径和图标路径" << std::endl;
        return -1;
    }
    return 0;
}

std::string categorySelector(){
    std::vector<std::string> categories = {"Network", "IDE", "Development"};
    std::cout << "请选择程序类别:" <<  std::endl;
    for (int i = 0; i < categories.size(); ++i) {
        std::cout << i << ":" << categories[i] << std::endl;
    }
    std::cout << "选择一个程序类别:";
    int categoryNumber;
    std::cin >> categoryNumber;
    if(categoryNumber >= categories.size())
    {
        std::cout << "输入的参数有误，请重新输入" << std::endl;
        return categorySelector();
    }
    else
    {
        return categories[categoryNumber];
    }
}

void createShortCut(std::string path, std::string name, std::string iconPath, std::string category)
{
    std::ofstream ofs("/usr/share/applications/" + name + ".desktop", std::ios::out);
    ofs << "[Desktop Entry]" << std::endl;
    ofs << "Name=" << name << std::endl;
    ofs << "Exec=" << path << std::endl;
    ofs << "Icon=" << iconPath << std::endl;
    ofs << "Type=Application" << std::endl;
    ofs << "Categories=" << category << ";" << std::endl;
    ofs.close();
}

int main(int argc, char** argv) {
    int ret = checkParams(argc,argv);
    if(ret == -1)
    {
        return -1;
    }

    std::string execPath = std::string(argv[1]);
    unsigned long lastSplitIdx = execPath.find_last_of('/');
    std::string appShortName = execPath.substr(lastSplitIdx);
    std::string appShortNameInput;
    std::cout << "请输入应用程序名称" << "（默认为:" << appShortName << "，输入Y确认，输入自定义的名字覆盖)：" ;
    std::cin >> appShortNameInput;
    if(appShortNameInput != "y")
    {
        appShortNameInput.erase(0,appShortNameInput.find_first_not_of(' '));
        appShortNameInput.erase(appShortNameInput.find_last_not_of(' ')+1);
        appShortName = appShortNameInput;
    }
    std::string iconPath = std::string(argv[2]);
    std::string category = categorySelector();
    createShortCut(execPath, appShortName, iconPath, category);
    return 0;
}
